package org.bluesky.job;

import org.bluesky.framework.constants.SystemConstants;
import org.bluesky.framework.entity.Article;
import org.bluesky.framework.service.ArticleService;
import org.bluesky.framework.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleService articleService;

    //每分钟更新一次
    @Scheduled(cron = "0 * * * * ?")
    public void updateViewCount(){
        //要执行的代码
        //获取redis中的浏览量
        Map<String,Integer> map = redisCache.getCacheMap(SystemConstants.REDIS_VIEW_COUNT_KEY);
        List<Article> articles = map.entrySet().stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());

        //更新到数据库
        articleService.updateBatchById(articles);
    }
}
